package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@RequestMapping("/admin/dish")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public Result addDish(@RequestBody DishDTO dishDTO){
        log.info("新增菜品: {}",dishDTO);
        dishService.addDishWithFlavor(dishDTO);



        //删除缓存数据
        String key = "dish_" + dishDTO.getCategoryId();
        deleteCacheData(key);


        return Result.success();
    }

    @GetMapping("/page")
    public Result<PageResult> DishPage(DishPageQueryDTO dishPageQueryDTO){
        log.info("分页查询菜品信息: {}",dishPageQueryDTO);
        PageResult pageResult = dishService.dishPage(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping
    public Result deleteDish(@RequestParam String ids){
        log.info("删除菜品: {}",ids);
        dishService.deleteDish(ids);

        //删除所有缓存数据
        deleteCacheData("dish_*");
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("查询菜品信息: {}",id);
        DishVO dishVO = dishService.getById(id);
        return Result.success(dishVO);

    }

    @PutMapping
    public Result updateDish(@RequestBody DishDTO dishDTO){
        log.info("修改菜品,内容:{}",dishDTO);
        dishService.updateDish(dishDTO);

        //删除所有缓存数据
        deleteCacheData("dish_*");
        return Result.success();
    }

    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("修改菜品状态: {},{}",status,id);
        dishService.startOrStop(status,id);

        //删除所有缓存数据
        deleteCacheData("dish_*");


        return Result.success();
    }


    @GetMapping("/list")
    public Result<List<Dish>> list(Long categoryId){
        log.info("查询菜品列表: {}",categoryId);
        List<Dish> list = dishService.findByCategoryId(categoryId);
        return Result.success(list);
    }

    private void deleteCacheData(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
